double .get().get() dict python

46

example_dict = {
  'key1': {
    'key2': 'test2',
    'key3': 'test3'
  }
}

example_dict.get('key1', {}).get('key2')

# This will return None if either key1 or key2 does not exist.

# Note that this could still raise an AttributeError if example_dict['key1'] exists but is not a dict (or a dict-like object with a get method). The try..except code you posted would raise a TypeError instead if example_dict['key1'] is unsubscriptable.

# Another difference is that the try...except short-circuits immediately after the first missing key. The chain of get calls does not.

Comments

Submit
0 Comments